<template>
  <div class="container">
    <div class="image-wrapper" ref="imageContainerRef">
      <img :src="currentImage" alt="" />
      <div class="hot-wrapper">
        <div
          v-for="(hotItem, hotIndex) in currentHotList"
          :key="hotItem.id"
          class="hot-item interact"
          :class="{ active: currentHotIndex === hotIndex }"
          :data-id="hotItem.id"
          :style="{
            width: `${hotItem.width}px`,
            height: `${hotItem.height}px`,
            transform: `translate(${hotItem.x}px, ${hotItem.y}px)`,
          }"
          @mousedown="currentHotIndex = hotIndex"
        ></div>
      </div>
    </div>
    <div class="footer">
      <el-input v-if="currentHotIndex !== -1" v-model="currentHotList[currentHotIndex].url"></el-input>
      <el-button type="primary" @click="addHot">添加热区</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </div>
</template>

<script setup>
import interact from 'interactjs';
//https://img30.360buyimg.com/sku/jfs/t1/271020/32/29381/106222/680ef32cF62dd8a18/6d21173b745d55e4.jpg.avif
//https://img30.360buyimg.com/sku/jfs/t1/282018/22/26522/122409/680a14b7Fdabcefa9/4105798a989ecc0a.jpg.avif
//https://img30.360buyimg.com/sku/jfs/t1/270508/18/27690/181812/680a14b7Ff072514a/a105e365757c8f74.jpg.avif
const imageList = ref([
  {
    id: getUuid(),
    image: 'https://img30.360buyimg.com/sku/jfs/t1/297874/37/3135/92793/681808f7F09e4dd2f/47b9a879ebc51167.jpg.avif',
    // 可点击的热区列表
    hotArea: [],
  },
]);
// 当前编辑的图片
const currentImageIndex = ref(0);
const currentImage = computed(() => {
  return imageList.value[currentImageIndex.value].image;
});
// 当前图片的热区列表
const currentHotList = computed(() => {
  return imageList.value[currentImageIndex.value].hotArea;
});
// 当前编辑的热区
const currentHotIndex = ref(-1);
const imageContainerRef = ref();

function addHot() {
  const top = imageContainerRef.value.scrollTop;
  const hotArea = imageList.value[currentImageIndex.value].hotArea;
  hotArea.push({
    id: getUuid(),
    url: '',
    x: 0,
    y: top,
    width: 100,
    height: 60,
  });
}

/**
 * 保存编辑的内容
 */
function save() {
  // 深拷贝
  const result = JSON.parse(JSON.stringify(imageList.value));
  for (const item of result) {
    for (const hotItem of item.hotArea) {
      // 将绝对大小转换为相对大小
      hotItem.x = hotItem.x / 500;
      hotItem.y = hotItem.y / 500;
      hotItem.width = hotItem.width / 500;
      hotItem.height = hotItem.height / 500;
    }
  }
  // eslint-disable-next-line no-undef
  localStorage.setItem('imageList', JSON.stringify(result));
  window.open('/#/preview/index', '_blank');
}

function onDel() {
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Delete' || e.key === 'Backspace') {
      const hotArea = imageList.value[currentImageIndex.value].hotArea;
      hotArea.splice(currentHotIndex.value, 1);
      currentHotIndex.value = -1;
    }
  });
}

onMounted(() => {
  initInteract();
  onDel();
});

/**
 * 初始化拖拽插件
 */
function initInteract() {
  interact('.interact')
    .draggable({
      // 平滑拖拽
      // inertia: true,
      modifiers: [
        interact.modifiers.restrictRect({
          restriction: 'parent',
          endOnly: true,
        }),
      ],
      listeners: {
        start(event) {
          // console.log(event.type, )
          const target = event.target;
          const hotId = target.getAttribute('data-id');
          currentHotIndex.value = currentHotList.value.findIndex((item) => item.id === hotId);
        },
        move(event) {
          // 当前拖拽的元素
          const currentHot = currentHotList.value[currentHotIndex.value];
          const x = currentHot.x + event.dx;
          const y = currentHot.y + event.dy;
          currentHot.x = x;
          currentHot.y = y;
        },
      },
    })
    .resizable({
      edges: { top: true, left: true, bottom: true, right: true },
      invert: 'negate',
      modifiers: [
        // keep the edges inside the parent
        interact.modifiers.restrictEdges({
          outer: 'parent',
        }),

        // 设置最小的尺寸
        interact.modifiers.restrictSize({
          min: { width: 100, height: 60 },
        }),
      ],
      listeners: {
        start(event) {
          const target = event.target;
          const hotId = target.getAttribute('data-id');
          currentHotIndex.value = currentHotList.value.findIndex((item) => item.id === hotId);
        },
        move(event) {
          const currentHot = currentHotList.value[currentHotIndex.value];
          const x = currentHot.x + event.deltaRect.left;
          const y = currentHot.y + event.deltaRect.top;
          currentHot.x = x;
          currentHot.y = y;
          currentHot.width = event.rect.width;
          currentHot.height = event.rect.height;
        },
      },
    });
}

function getUuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0,
      v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}
</script>

<style scoped lang="scss">
.container {
}

.image-wrapper {
  border: 2px dashed #094fd2;
  width: 504px;
  height: 400px;
  margin: 0 auto;
  position: relative;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 0;
    position: absolute;
  }

  font-size: 0;

  img {
    width: 100%;
  }
}

.hot-wrapper {
  //border: 1px dashed red;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;

  .hot-item {
    background: #ff000055;
    position: absolute;
    left: 0;
    top: 0;

    &.active {
      outline: 2px dashed #094fd2;
    }
  }
}

.footer {
  text-align: center;
  margin-top: 20px;
}
</style>
